package com.jcodecraeer.xrecyclerview;


import com.jcodecraeer.xrecyclerview.progressindicator.AVLoadingIndicatorView;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.Date;

public class ArrowRefreshHeader extends DirectionalLayout implements BaseRefreshHeader {
    private static final String XR_REFRESH_KEY = "XR_REFRESH_KEY";
    private static final String XR_REFRESH_TIME_KEY = "XR_REFRESH_TIME_KEY";
    private static final int ROTATE_ANIM_DURATION = 180;

    private AVLoadingIndicatorView progressView;
    private SimpleViewSwitcher mProgressBar;
    private DirectionalLayout mContainer;
    private DirectionalLayout mHeaderRefreshTimeContainer;
    private Component mComponent;
    private Image mArrowImageView;
    private Text mStatusTextView;
    private Text mHeaderTimeView;

    private Animator mRotateUpAnim;
    private Animator mRotateDownAnim;
    private int mState = STATE_NORMAL;
    public int mMeasuredHeight;
    private String customRefreshPsKey = null;

    public void destroy(){
        mProgressBar = null;
        if(progressView != null){
            progressView.destroy();
            progressView = null;
        }
    }

    public ArrowRefreshHeader(Context context) {
        this(context,null,null);
    }

    public ArrowRefreshHeader(Context context, AttrSet attrSet) {
        this(context, attrSet,null);
    }

    public ArrowRefreshHeader(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        initView(context, attrSet, styleName);
    }

    public void setRefreshTimeVisible(boolean show){
        if(mHeaderRefreshTimeContainer != null)
            mHeaderRefreshTimeContainer.setVisibility(show?VISIBLE:HIDE);
    }

    public void setXrRefreshTimeKey(String keyName){
        if(keyName != null){
            customRefreshPsKey = keyName;
        }
    }

    private void initView(Context context, AttrSet attrSet, String styleName) {
        LayoutScatter scatter = LayoutScatter.getInstance(context);
        mContainer = (DirectionalLayout) scatter.parse(ResourceTable.Layout_listview_header, null, false);

        mHeaderRefreshTimeContainer = (DirectionalLayout)mContainer.findComponentById(ResourceTable.Id_header_refresh_time_container);
        LayoutConfig lp = new LayoutConfig(LayoutConfig.MATCH_PARENT,LayoutConfig.MATCH_CONTENT);
        lp.setMargins(0,0,0,0);
        this.setPadding(0,0,0,0);
        this.setLayoutConfig(lp);

        addComponent(mContainer,new LayoutConfig(LayoutConfig.MATCH_PARENT,0));
        setAlignment(TextAlignment.BOTTOM);

        mArrowImageView = (Image)mContainer.findComponentById(ResourceTable.Id_listview_header_arrow);
        mStatusTextView = (Text)mContainer.findComponentById(ResourceTable.Id_refresh_status_textview);
        mHeaderTimeView = (Text)mContainer.findComponentById(ResourceTable.Id_last_refresh_time);

        //init the progress view
        mProgressBar = (SimpleViewSwitcher)mContainer.findComponentById(ResourceTable.Id_listview_header_progressbar);
        progressView = new AVLoadingIndicatorView(context);
        progressView.setIndicatorColor(0xffB5B5B5);
        progressView.setIndicatorId(ProgressStyle.BallSpinFadeLoader);
        if(mProgressBar != null){
            mProgressBar.setView(progressView);
            progressView.applyAnimation();
        }
        estimateSize(ComponentContainer.LayoutConfig.MATCH_CONTENT,ComponentContainer.LayoutConfig.MATCH_CONTENT);
        mMeasuredHeight = getEstimatedHeight();
    }

    public void setProgressStyle(int style){
        progressView = new  AVLoadingIndicatorView(getContext());
        if(style == ProgressStyle.SysProgress){
            progressView.setIndicatorColor(Color.RED.getValue());
        }else {
            progressView.setIndicatorColor(0xffB5B5B5);
        }
        progressView.setIndicatorId(style);
        mProgressBar.setView(progressView);
        progressView.applyAnimation();
    }

    public void setIndicatorColor(int color){
        progressView.setIndicatorColor(color);
        this.invalidate();
    }

    public void setArrowImageView(int resid){
        mArrowImageView.setPixelMap(resid);
    }

    public void setState(int state) {
        if(state == mState){
            return;
        }

        if(state == STATE_REFRESHING){// 显示进度
//            mArrowImageView.clearAnimation();
            mArrowImageView.setVisibility(INVISIBLE);
            if(mProgressBar != null){
                mProgressBar.setVisibility(VISIBLE);
            }
            smoothScrollTo(mMeasuredHeight);
        }else if(state == STATE_DONE){
            mArrowImageView.setVisibility(INVISIBLE);
            if(mProgressBar != null){
                mProgressBar.setVisibility(INVISIBLE);
            }
        }else {// 显示箭头图片
            mArrowImageView.setVisibility(VISIBLE);
            if(mProgressBar != null){
                mProgressBar.setVisibility(INVISIBLE);
            }
        }

        mHeaderTimeView.setText(friendlyTime(getLastRefreshTime()));
        switch (state){
            case STATE_NORMAL:
                if (mState == STATE_RELEASE_TO_REFRESH) {
//                    mArrowImageView.startAnimation(mRotateDownAnim);
                }
                if (mState == STATE_REFRESHING) {
//                    mArrowImageView.clearAnimation();
                }
                mArrowImageView.setRotation(0);
                mStatusTextView.setText("下拉刷新");
                break;
            case STATE_RELEASE_TO_REFRESH:
                if (mState != STATE_RELEASE_TO_REFRESH) {
                    mArrowImageView.setRotation(180);
                    mStatusTextView.setText("释放立即刷新");
                }
                break;
            case STATE_REFRESHING:
                mStatusTextView.setText("正在刷新...");
                break;
            case STATE_DONE:
                mStatusTextView.setText("刷新完成");
                break;
            default:
                break;
        }
        mState = state;
    }

    public int getState() {
        return mState;
    }

    private long getLastRefreshTime(){
        String spKeyName = XR_REFRESH_KEY;
        if(customRefreshPsKey != null){
            spKeyName = customRefreshPsKey;
        }
        DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
        Preferences preferences = databaseHelper.getPreferences(spKeyName);
        return preferences.getLong(XR_REFRESH_TIME_KEY,new Date().getTime());

    }

    private void saveLastRefreshTime(long refreshTime){
        String spKeyName = XR_REFRESH_KEY;
        if(customRefreshPsKey != null){
            spKeyName = customRefreshPsKey;
        }
        DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
        Preferences preferences = databaseHelper.getPreferences(spKeyName);
        preferences.putLong(XR_REFRESH_TIME_KEY,refreshTime).flush();
    }

    @Override
    public void refreshComplete() {
        mHeaderTimeView.setText(friendlyTime(getLastRefreshTime()));
        saveLastRefreshTime(System.currentTimeMillis());
        setState(STATE_DONE);
        reset();
    }

    public void setVisibleHeight(int height){
        if(height <= 0){
            height = 0;
        }else if(height >400){
            height = 400;
        }
        LayoutConfig lp = (LayoutConfig)mContainer.getLayoutConfig();
        lp.height = height;
        mContainer.setLayoutConfig(lp);
    }

    public int getVisibleHeight() {
        LayoutConfig lp = (LayoutConfig)mContainer.getLayoutConfig();
        return lp.height;
    }

    @Override
    public void onMove(float delta) {
        if(getVisibleHeight() > 0 || delta > 0){
            setVisibleHeight((int)delta);
            if(mState <= STATE_RELEASE_TO_REFRESH){// 未处于刷新状态，更新箭头
                if (getVisibleHeight() > mMeasuredHeight) {
                    setState(STATE_RELEASE_TO_REFRESH);
                }else {
                    setState(STATE_NORMAL);
                }
            }
        }
    }

    @Override
    public boolean releaseAction() {
        boolean isOnRefresh = false;
        int height = getVisibleHeight();
        if(height ==0){
            isOnRefresh = false;
        }

        if(getVisibleHeight() > mMeasuredHeight && mState < STATE_REFRESHING){
            setState(STATE_REFRESHING);
            isOnRefresh = true;
        }
        if (mState != STATE_REFRESHING) {
            smoothScrollTo(0);
        }

        if (mState == STATE_REFRESHING) {
            int destHeight = mMeasuredHeight;
            setVisibleHeight(destHeight);
        }

        return isOnRefresh;
    }

    public void reset(){
        smoothScrollTo(0);
        setState(STATE_NORMAL);
    }

    private void smoothScrollTo(int destHeight) {
        setVisibleHeight(0);
        postLayout();
        invalidate();
    }

    public static String friendlyTime(Date time) {
        return friendlyTime(time.getTime());
    }

    public static String friendlyTime(long time) {
        //获取time距离当前的秒数
        int ct = (int)((System.currentTimeMillis() - time)/1000);

        if(ct == 0) {
            return "刚刚";
        }

        if(ct > 0 && ct < 60) {
            return ct + "秒前";
        }

        if(ct >= 60 && ct < 3600) {
            return Math.max(ct / 60,1) + "分钟前";
        }
        if(ct >= 3600 && ct < 86400)
            return ct / 3600 + "小时前";
        if(ct >= 86400 && ct < 2592000){ //86400 * 30
            int day = ct / 86400 ;
            return day + "天前";
        }
        if(ct >= 2592000 && ct < 31104000) { //86400 * 30
            return ct / 2592000 + "月前";
        }
        return ct / 31104000 + "年前";
    }
}
